import Http from '@/api/helper/http'
import { createAPIFn, fnName } from '@/api/helper/utils'

const MODULES = ['account']

const httpMap = MODULES.reduce((map, module) => {
  map[module] = new Http(module)
  return map
}, {})

/** 初始化API */
async function setupApiFns() {
  // 动态导入所有ApiMsg
  async function fetchModules() {
    const msgMap = {}
    for (const m of MODULES) {
      const module = await import(`@/api/modules/${m}/index.ts`)
      msgMap[m] = module.default
    }
    return msgMap
  }
  const moduleToMsgs: { [propName: string]: Array<string> } = await fetchModules()
  return Object.entries(moduleToMsgs).reduce((pre, [module, msgs]) => {
    msgs.forEach((msg) => {
      /** 重名则拼接上模块名 */
      const isExist = !!pre[fnName(msg)]
      if (isExist) {
        const moduleName = module.slice(0, 1).toUpperCase() + module.slice(1)
        pre[`${moduleName}${fnName(msg)}`] = createAPIFn(httpMap[module], msg)
      }
      else { pre[fnName(msg)] = createAPIFn(httpMap[module], msg) }
    })
    return pre
  }, {}) as any
}
export default await setupApiFns()
